package com.beaglebros.SDWatch;

import java.util.List;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

public class NotificationClicked extends BroadcastReceiver {

	private static final String TAG = SDWatch.TAG;

	@Override
	public void onReceive(Context context, Intent intent) {
		Uri idata = intent.getData();
		int id;
		try {
			id = Integer.parseInt(idata.getFragment());
		} catch (NumberFormatException e) {
			Log.wtf(TAG, "Bogus notification");
			return;
		}
		NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		nm.cancel(id);
		try {
			new Prefs().freeId(id);
		} catch (BitmapOutOfBoundsException e) {
			Log.e(TAG, "id to free too large");
			return;
		}
		String pkg = idata.getSchemeSpecificPart();
		openApplicationInfo(context, pkg);
	}

	private void openApplicationInfo(Context context, String pkg) {
		Intent oi = new Intent(Intent.ACTION_VIEW);
		
		switch (Build.VERSION.SDK_INT) {
		case 1:
		case 2:
		case 3:
		case 4:
		case 5:
		case 6:
		case 7:
			// Pre-Froyo
			// it makes no sense for this app to run here, but, for the record, this is supposed to be the appropriate intent:
			
			//it.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
			//it.putExtra("com.android.settings.ApplicationPkgName", pli.name);
			
			// instead, we'll just return without doing anything
			return;
			//break;
		case 8:
			// Froyo
			oi.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
			oi.putExtra("pkg", pkg);
			break;
		case 9:
		default:
			// Gingerbread and later
			oi.setClassName("com.android.settings", "com.android.settings.applications.InstalledAppDetails");
			oi.setData(Uri.fromParts("pkg", pkg, null));
			break;
		}

		oi.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        List<ResolveInfo> acts = context.getPackageManager().queryIntentActivities(oi, 0);
        if (acts.size() > 0) {
	        context.startActivity(oi);
        }
	}
	
}